/**
 * 
 */
package freedom.sample.event;

import org.springframework.beans.BeanUtils;

import com.fasterxml.jackson.core.JsonProcessingException;

import freedom.sample.model.EventContext;
import freedom.sample.model.MarketActivity;
import freedom.sample.service.DeliverService;
import freedom.sample.service.EventService;
import freedom.sample.util.XmlUtil;

/**
 * @author charlie
 *
 */
public abstract class BaseEvent implements PerfectExecutable {
	
	protected EventService eventService;
	protected DeliverService deliverService;//需注入DeliverServiceMutiImpl
	protected EventContext eventContext;
	protected boolean recordEventContextAllowed = true;
	protected boolean recordMarketingActivityAllowed = true;
	
	public BaseEvent() {
		super();
	}
	
	public BaseEvent(EventService eventService, DeliverService deliverService) {
		super();
		this.eventService = eventService;
		this.deliverService = deliverService;
	}

	public void copyProps(Object... objects) {
		if(objects != null)
		for (Object object : objects) {
			if(object != null)
			BeanUtils.copyProperties(object, this);
		}
	}

	/* (non-Javadoc)
	 * @see freedom.sample.Event#recordContext()
	 */
	@Override
	public void record() throws JsonProcessingException {
		if(this.recordEventContextAllowed) {
			EventContext ctx = new EventContext(this.getClass().getName(), XmlUtil.genXml(this));
			eventContext = eventService.save(ctx);
		}
	}
	
	/**
	 * @param marketingActivity
	 */
	public void handle(MarketActivity marketingActivity) {
		if(this.recordMarketingActivityAllowed) {
			if(this.recordEventContextAllowed && this.eventContext != null)
				System.out.println("hit. eventContext: " + this.eventContext);
				marketingActivity.setEventContextId(this.eventContext.getId());
			eventService.save(marketingActivity);
		}
		deliverService.deliver(marketingActivity);
	}

	/**
	 * @param eventService the eventService to set
	 */
	public void setEventService(EventService eventService) {
		this.eventService = eventService;
	}

	/**
	 * @param eventContext the eventContext to set
	 */
	public void setEventContext(EventContext eventContext) {
		this.eventContext = eventContext;
	}

	/**
	 * @param recordEventContextAllowed the recordEventContextAllowed to set
	 */
	public void setRecordEventContextAllowed(boolean recordEventContextAllowed) {
		this.recordEventContextAllowed = recordEventContextAllowed;
	}

	/**
	 * @param recordMarketingActivityAllowed the recordMarketingActivityAllowed to set
	 */
	public void setRecordMarketingActivityAllowed(boolean recordMarketingActivityAllowed) {
		this.recordMarketingActivityAllowed = recordMarketingActivityAllowed;
	}

}
